package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.HospitalFeignClient;
import com.atguigu.yygh.client.PatientFeignClient;
import com.atguigu.yygh.cmn.feign.DictFeignClient;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderMapper;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.WXService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.rabbitmq.config.MQProperties;
import com.atguigu.yygh.rabbitmq.service.RabbitmqService;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.SmsVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.internal.bind.v2.TODO;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author zhmwi
 * @Date 2021/7/21
 * @Dersciption
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private RabbitmqService rabbitmqService;
    @Autowired
    private WXService wxService;

    //创建订单并声称订单id的方法
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //1.获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        if (patient == null){
            throw new YyghException();
        }

        //2.获取下单信息 排班规则信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        if (scheduleOrderVo == null){
            throw new YyghException();
        }
        //2.1验证当前时间是否是可以预约的时间段
        //预约开始的时间是现在之后 -->还没到预约时间
        //预约结束的时间是现在之前 -->已经过期了
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getStopTime()).isBeforeNow()){
            throw new YyghException();
        }
        //2.2.验证号源数量
        if (scheduleOrderVo.getAvailableNumber() <= 0){
            throw new YyghException();
        }
        //3.下单 封装数据存入数据库
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
        //生成订单交易号
        String outTradeNo = System.currentTimeMillis()+""+new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //4封装参数，然后通过接口去医院预约下单
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");

        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        if (result.getInteger("code") == 200){
            //医院返回map
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            //更新
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //5.下单成功 更新排班信息(减库存) 与 发送短信(MQ)
            //TODO

            //发送mq 更新号源信息和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //短信提示参数
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            smsVo.setParam(param);
            //mq参数
            orderMqVo.setSmsVo(smsVo);
            rabbitmqService.sendMessage(MQProperties.EXCHANGE_DIRECT_ORDER, MQProperties.ROUTING_ORDER, orderMqVo);
        }else{
            System.err.println("下单失败");
            throw new YyghException(20001,"下单失败");
        }
        return orderInfo.getId();
    }

    //带条件带分页查询订单列表
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (orderQueryVo != null){
            //orderQueryVo获取条件值
            String name = orderQueryVo.getKeyword(); //医院名称
            Long patientId = orderQueryVo.getPatientId(); //就诊人名称
            String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
            String reserveDate = orderQueryVo.getReserveDate();//安排时间
            String createTimeBegin = orderQueryVo.getCreateTimeBegin();
            String createTimeEnd = orderQueryVo.getCreateTimeEnd();

            if(!StringUtils.isEmpty(name)) {
                wrapper.like("hosname",name);
            }
            if(!StringUtils.isEmpty(patientId)) {
                wrapper.eq("patient_id",patientId);
            }
            if(!StringUtils.isEmpty(orderStatus)) {
                wrapper.eq("order_status",orderStatus);
            }
            if(!StringUtils.isEmpty(reserveDate)) {
                wrapper.ge("reserve_date",reserveDate);
            }
            if(!StringUtils.isEmpty(createTimeBegin)) {
                wrapper.ge("create_time",createTimeBegin);
            }
            if(!StringUtils.isEmpty(createTimeEnd)) {
                wrapper.le("create_time",createTimeEnd);
            }
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);

        pages.getRecords().stream().forEach(item->{
            this.packOrderInfo(item);
        });

        return pages;
    }

    //取消订单
    @Override
    public Boolean cancelOrder(Long orderId) {
        //根据orderId查询订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo == null){
            throw new YyghException();
        }
        //查询退号时间 与 当前时间对比
        DateTime quitTime = new DateTime( orderInfo.getQuitTime());
        if(quitTime.isBeforeNow()){
            //不能退了
            throw new YyghException(20001,"已过退号时间");
        }
        //封装参数 httpclient 调用医院接口,更改订单状态
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("hosRecordId",orderInfo.getHosRecordId());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        paramMap.put("sign", "");
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/updateCancelStatus");
        if (result.getInteger("code")!=200){
            //判断是否查询到更新支付状态
            throw new YyghException(20001,result.getString("message"));
        }else{
            //判断是否支付,已支付进行退款
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
                Boolean refund = wxService.refund(orderId);
                if (refund == false){
                    throw new YyghException(20001,"退款失败");
                }
            }
            //更改订单状态 为取消
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //释放号源 可预约数mq中+1
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(orderInfo.getPatientPhone());
            orderMqVo.setSmsVo(smsVo);
            rabbitmqService.sendMessage(MQProperties.EXCHANGE_DIRECT_ORDER,MQProperties.ROUTING_ORDER,orderMqVo);
        }
        return true;
    }

    //订单提醒
    @Override
    public void patientTips() {
        //查询订单信息
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for(OrderInfo orderInfo : orderInfoList) {
            //短信提示
            SmsVo smsVo = new SmsVo();
            smsVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            smsVo.setParam(param);
            rabbitmqService.sendMessage(MQProperties.EXCHANGE_DIRECT_MSM, MQProperties.ROUTING_MSM_ITEM, smsVo);
        }
    }


        //
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        Integer orderStatus = orderInfo.getOrderStatus();
        String status = OrderStatusEnum.getStatusNameByStatus(orderStatus);
        orderInfo.getParam().put("orderStatusString",status);
        return orderInfo;
    }
}
